package cn.fansunion.concurrent.threadabc;

import java.util.concurrent.atomic.AtomicInteger;

//使用AtimicInteger，原子CAS，切换正在打印的Thread
public class ThreadABCByAtomic {
	public static void main(String[] args) throws InterruptedException {

		Thread a = new Thread(new PrintRunnable("A", 1, 2));
		Thread b = new Thread(new PrintRunnable("B", 2, 3));
		Thread c = new Thread(new PrintRunnable("C", 3, 1));
		a.start();
		b.start();
		c.start();
		a.join();
		b.join();
		c.join();
	}

	static class PrintRunnable implements Runnable {
		private String str;
		private static AtomicInteger runFlag = new AtomicInteger(1);
		private int mySequence;
		private int next;

		private PrintRunnable(String str, int mySequence, int next) {
			this.str = str;
			this.mySequence = mySequence;
			this.next = next;
		}

		@Override
		public void run() {
			//while循环,性能很差
			while (true) {
				if (runFlag.get() == mySequence)
					print();
			}
		}

		public void print() {
			System.out.print(str);
			if (next < mySequence)
				System.out.println();

			// cas设置下一个执行序号
			runFlag.compareAndSet(mySequence, next);
		}
	}
}